const express = require('express');
const router = express.Router();
const { pool } = require('../config/db'); // Fix the import path
const auth = require('../middleware/auth');

// 获取所有课程
router.get('/', auth, async (req, res) => {
  try {
    // 检查权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足' });
    }
    
    const [courses] = await pool.query(`
      SELECT id, name, credits
      FROM courses
      ORDER BY name
    `);
    
    res.json(courses);
  } catch (error) {
    console.error('获取课程列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 添加新课程
router.post('/', auth, async (req, res) => {
  try {
    // 检查权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足' });
    }
    
    const { name, credits, courseCode, teacherId, startTime, endTime, weekday, weeks, semester } = req.body;
    
    // 验证必填字段
    if (!name || !credits || !courseCode || !teacherId) {
      return res.status(400).json({ message: '请提供所有必要信息' });
    }
    
    // 使用提交的学期值，不进行格式化或默认值替换
    
    // 添加新课程
    const [result] = await pool.query(`
      INSERT INTO courses (name, credits, courseCode, teacherId, startTime, endTime, weekday, weeks, semester)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    `, [name, credits, courseCode, teacherId, startTime, endTime, weekday, weeks || '1-16', semester]);
    
    const courseId = result.insertId;
    
    res.status(201).json({ id: courseId, message: '课程添加成功' });
  } catch (error) {
    console.error('添加课程失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取单个课程
router.get('/:id', auth, async (req, res) => {
  try {
    // 检查权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足' });
    }
    
    const courseId = req.params.id;
    
    const [courses] = await pool.query(`
      SELECT id, name, credits
      FROM courses
      WHERE id = ?
    `, [courseId]);
    
    if (courses.length === 0) {
      return res.status(404).json({ message: '课程不存在' });
    }
    
    res.json(courses[0]);
  } catch (error) {
    console.error('获取课程详情失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新课程
router.put('/:id', auth, async (req, res) => {
  try {
    // 检查权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足' });
    }
    
    const courseId = req.params.id;
    const { name, credits } = req.body;
    
    // 验证必要参数
    if (!name || !credits) {
      return res.status(400).json({ message: '缺少必要参数' });
    }
    
    // 检查课程是否存在
    const [existingCourses] = await pool.query(`
      SELECT id FROM courses WHERE id = ?
    `, [courseId]);
    
    if (existingCourses.length === 0) {
      return res.status(404).json({ message: '课程不存在' });
    }
    
    // 检查课程名称是否已被其他课程使用
    const [nameConflicts] = await pool.query(`
      SELECT id FROM courses WHERE name = ? AND id != ?
    `, [name, courseId]);
    
    if (nameConflicts.length > 0) {
      return res.status(400).json({ message: '课程名称已存在' });
    }
    
    // 更新课程
    await pool.query(`
      UPDATE courses
      SET name = ?, credits = ?
      WHERE id = ?
    `, [name, credits, courseId]);
    
    res.json({ 
      id: parseInt(courseId),
      name,
      credits
    });
  } catch (error) {
    console.error('更新课程失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除课程
router.delete('/:id', auth, async (req, res) => {
  try {
    // 检查权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足' });
    }
    
    const courseId = req.params.id;
    
    // 检查课程是否存在
    const [existingCourses] = await pool.query(`
      SELECT id FROM courses WHERE id = ?
    `, [courseId]);
    
    if (existingCourses.length === 0) {
      return res.status(404).json({ message: '课程不存在' });
    }
    
    // 检查课程是否被使用
    const [usedCourses] = await pool.query(`
      SELECT id FROM timetables WHERE courseId = ?
    `, [courseId]);
    
    if (usedCourses.length > 0) {
      return res.status(400).json({ message: '课程已被课表使用，无法删除' });
    }
    
    // 删除课程
    await pool.query(`
      DELETE FROM courses WHERE id = ?
    `, [courseId]);
    
    res.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除课程失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router;